package com.zlzlib.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

/**
 * 公共配置  @Configuration
 *
 * @DateTime: 2023/6/2 10:32
 * @Author zlz
 * @Version 1.0
 */
public abstract class CommonMvcConfig extends WebMvcConfigurationSupport {

    @Value("${spring.jackson.date-format}")
    private String dateFormat;
    @Value("${spring.jackson.time-zone}")
    private String timeZone;

    /**
     * 统一前缀
     *
     * @return 前缀
     */
    protected abstract String getBaseUrlPath();

    /**
     * 请求路径添加统一前缀
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix(getBaseUrlPath(), c -> c.isAnnotationPresent(BaseUrlHead.class));
    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = converter.getObjectMapper();
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        //序列化不包含为空的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.registerModule(simpleModule);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //序列化时间的格式
        objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));
        objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone));
        converter.setObjectMapper(objectMapper);
        converters.add(0, converter);
    }


}
